import { defineStore } from 'pinia'
import { login, logout, getUserInfo } from '../../api/user'

export const useUserStore = defineStore('user', {
  state: () => ({
    token: localStorage.getItem('token') || '',
    userInfo: {}
  }),
  
  getters: {
    isLoggedIn: (state) => !!state.token
  },
  
  actions: {
    async login(loginForm) {
      const { data } = await login(loginForm)
      this.token = data.token
      localStorage.setItem('token', data.token)
      await this.getUserInfo()
    },
    
    async getUserInfo() {
      const { data } = await getUserInfo()
      this.userInfo = data
    },
    
    async logout() {
      await logout()
      this.token = ''
      this.userInfo = {}
      localStorage.removeItem('token')
    }
  }
}) 